import { User } from './../entitys/User';
import redis, {setExpire,getObject} from "../redis"
import  {v4} from "uuid"
import { Service } from "typedi"

const KEY_PREFIX = "token:"
const TOKEN_EXPIRE_AT = 1800 
@Service()
export default class AuthService{

    async saveUserToRedis(user:any):Promise<string>{
         let uuid = v4()
         await setExpire(KEY_PREFIX + uuid,JSON.stringify(user),TOKEN_EXPIRE_AT)
        return uuid
    }
    async checkToken(token:string):Promise<User>{
        try {
            let user:User = await getObject<User>(KEY_PREFIX + token)
            if(!user){
                return Promise.reject(false)
            }
            await redis.expire(KEY_PREFIX+token,TOKEN_EXPIRE_AT) 
            return user    
        } catch (error) {
            return Promise.reject(error)
        }
    }

}
